<template>
  <div class="a-charts" ref="charts"></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts/core'
import { TitleComponent, DataZoomComponent, ToolboxComponent, TooltipComponent, GridComponent, LegendComponent } from 'echarts/components'
import { PieChart, RadarChart, LineChart, BarChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { onMounted, onUnmounted, ref, watch } from 'vue'

echarts.use([PieChart, RadarChart, BarChart, TitleComponent, DataZoomComponent, ToolboxComponent, TooltipComponent, GridComponent, LegendComponent, LineChart, CanvasRenderer, UniversalTransition])

defineOptions({
  name: 'a-charts'
})

interface Props {
  option: echarts.EChartsCoreOption
}

const props = defineProps<Props>()

const charts = ref<HTMLElement | null>(null)
let charstObject: echarts.EChartsType
function resize() {
  charstObject.resize()
}

onMounted(() => {
  watch(
    () => props.option,
    () => {
      if (props.option) {
        echarts.dispose(charts.value!)
        charstObject = echarts.init(charts.value!)
        charstObject.setOption(props.option)
        window.addEventListener('resize', resize)
      }
    },
    { immediate: true, deep: true }
  )
})

onUnmounted(() => {
  window.removeEventListener('reisze', charstObject ? resize : function () {})
})
</script>
